package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.entity.FirmwareUpgradeBean;
import com.qiantu.api.entity.FirmwareUpgradeInfoBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.FirmwareUpgradeInfoEvent;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class FirmwareUpdateActivity extends AppActivity {

    private View versionInfo;
    private ImageView iconHasUpdate;
    private ImageView iconRotate;
    private TextView tvUpgrading;
    private TextView tvCurrentVersion;
    private TextView tvNewestVersion;
    private TextView tvUpdateContent;
    //    private TextView tvProgress;
//    private ProgressBar progressBar;
    private View btnUpdate;
    private String serialNo;
    private FirmwareUpgradeInfoBean mFirmwareUpgradeInfoBean;
    private Handler mHandler;
    private RotateAnimation mRotateAnimation;
    private String queryCode;
    private int upgradeType;

    @Log
    public static void start(Context context, String serialNo, int upgradeType) {
        Intent intent = new Intent(context, FirmwareUpdateActivity.class);
        intent.putExtra("serialNo", serialNo);
        intent.putExtra("upgradeType", upgradeType);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_firmware_update;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        serialNo = getString("serialNo");
        upgradeType = getInt("upgradeType");
        versionInfo = findViewById(R.id.version_info);
        iconHasUpdate = findViewById(R.id.icon_has_update);
        iconRotate = findViewById(R.id.icon_rotate);
        tvUpgrading = findViewById(R.id.tv_upgrading);
        tvCurrentVersion = findViewById(R.id.tv_current_version);
        tvNewestVersion = findViewById(R.id.tv_newest_version);
        tvUpdateContent = findViewById(R.id.tv_update_content);
//        tvProgress = findViewById(R.id.tv_progress);
//        progressBar = findViewById(R.id.progress_bar);
        btnUpdate = findViewById(R.id.btn_update);
        setOnClickListener(R.id.btn_update);
    }

    @Override
    protected void initData() {
        LLHttpManager.deviceUpgradeInfo(this, upgradeType, serialNo, new HttpCallback<HttpData<FirmwareUpgradeInfoBean>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.common_loading));
            }

            @Override
            public void onSucceed(HttpData<FirmwareUpgradeInfoBean> result) {
                mFirmwareUpgradeInfoBean = result.getData();
                updateView();
//                /**
//                 * 正在下载 : 2
//                 * 下载完成 : 3
//                 * 更新中 : 5
//                 */
//                if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 2
//                        || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 3
//                        || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 5) {
//                    if (mHandler == null) {
//                        mHandler = new Handler();
//                    }
//                    mHandler.postDelayed(queryRunnable, 800);
//                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void updateView() {
        versionInfo.setVisibility(View.VISIBLE);
        tvCurrentVersion.setText(getString(R.string.firmware_current_version_holder, mFirmwareUpgradeInfoBean.getCurrentVersion()));
        if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 6
                || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 8
                || TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getUpgradeVersion())) {
            needUpdate(false);
        } else {
            if((TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getCurrentVersion()) && TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getUpgradeVersion()))
                || TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getUpgradeVersion())){
                needUpdate(false);
                return;
            }
            if(TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getCurrentVersion()) && !TextUtils.isEmpty(mFirmwareUpgradeInfoBean.getUpgradeVersion())){
                needUpdate(true);
                return;
            }
            String[] currentVersion = mFirmwareUpgradeInfoBean.getCurrentVersion().split("\\.");
            String[] upgradeVersion = mFirmwareUpgradeInfoBean.getUpgradeVersion().split("\\.");
            needUpdate(compareVersion(currentVersion, upgradeVersion));
        }
    }

    /**
     * 版本号必须是两个点以上
     *
     * @param currentVersion 当前版本号
     * @param upgradeVersion 最新版本号
     * @return
     */
    private boolean compareVersion(String[] currentVersion, String[] upgradeVersion) {
        int size = Math.max(currentVersion.length, upgradeVersion.length);
        String[] currentVersionNew = new String[size];
        String[] upgradeVersionNew = new String[size];
        for (int i = 0; i < size; i++) {
            if (i < currentVersion.length) {
                currentVersionNew[i] = currentVersion[i];
            } else {
                currentVersionNew[i] = "0";
            }
            if (i < upgradeVersion.length) {
                upgradeVersionNew[i] = upgradeVersion[i];
            } else {
                upgradeVersionNew[i] = "0";
            }
        }
        if (size < 3)
            return false;
        for (int i = 0; i < size; i++) {
            int currentVersionNum = Integer.parseInt(currentVersionNew[i]);
            int upgradeVersionNum = Integer.parseInt(upgradeVersionNew[i]);
            if (upgradeVersionNum < currentVersionNum)
                return false;
            if (upgradeVersionNum > currentVersionNum)
                return true;
        }
        //相等
        return false;
    }

    private void needUpdate(Boolean needUpdate) {
        if (needUpdate) {
            iconHasUpdate.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_remind_renew_1));
            iconRotate.setVisibility(View.VISIBLE);
            String upgradeVersion = mFirmwareUpgradeInfoBean.getUpgradeVersion();
            if (!TextUtils.isEmpty(upgradeVersion)) {
                tvNewestVersion.setText(getString(R.string.firmware_newest_version_holder, upgradeVersion));
            } else {
                tvNewestVersion.setText(null);
            }
            /**
             * 状态类型,可用值:
             * 待更新 : 0 ,
             * 自动更新 : 1 ,
             * 正在下载 : 2 ,
             * 下载完成 : 3 ,
             * 下载失败 : 4 ,
             * 更新中 : 5 ,
             * 更新完成 : 6 ,
             * 更新失败 : 7 ,
             * 暂无更新 : 8
             */
            if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 2 || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 3 || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 5) {
//                tvProgress.setVisibility(View.VISIBLE);
//                progressBar.setVisibility(View.VISIBLE);
                btnUpdate.setVisibility(View.GONE);
                startRotateAnimation();
//                tvProgress.setText(mFirmwareUpgradeInfoBean.getStep() + "%");
//                progressBar.setProgress(mFirmwareUpgradeInfoBean.getStep());
            } else if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 0) {
//                tvProgress.setVisibility(View.GONE);
//                progressBar.setVisibility(View.GONE);
                btnUpdate.setVisibility(View.VISIBLE);
                stopRotateAnimation();
            } else if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 4 || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 7) {
                showUpdateResultDialog(false);
            } else if (mFirmwareUpgradeInfoBean.getUpgradeStateType() == 6 || mFirmwareUpgradeInfoBean.getUpgradeStateType() == 8) {
                showUpdateResultDialog(true);
            }
            tvUpdateContent.setVisibility(View.VISIBLE);
            tvUpdateContent.setText(mFirmwareUpgradeInfoBean.getDescription());
        } else {
            iconHasUpdate.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_remind_correct));
            iconRotate.setVisibility(View.GONE);
            stopRotateAnimation();
            tvNewestVersion.setText(R.string.no_update);
            btnUpdate.setVisibility(View.GONE);
            tvUpdateContent.setVisibility(View.GONE);
            if (mFirmwareUpgradeInfoBean.getStep() == 100) {
                showUpdateResultDialog(true);
            }
        }
    }


    private BaseDialog mResultDialog;
    private ConfirmHintDialog.Builder mResultDialogBuilder;

    private void showUpdateResultDialog(boolean isSuccess) {
        if (mResultDialog == null) {
            mResultDialogBuilder = new ConfirmHintDialog.Builder(this);
            mResultDialog = mResultDialogBuilder
                    .setRightBtnText(getResources().getString(R.string.confirm_text))
                    .create();
        }
        if (isSuccess) {
            mResultDialogBuilder.setHint(getString(R.string.upgrade_complete));
            mResultDialogBuilder.setContent(getString(R.string.upgrade_complete_hint));
            mResultDialogBuilder.setHintIcon(R.drawable.update_drawable);
        } else {
            mResultDialogBuilder.setHint(getString(R.string.upgrade_failed));
            mResultDialogBuilder.setContent(getString(R.string.upgrade_failed_hint));
            mResultDialogBuilder.setHintIcon(R.attr.icon_remind_renew_3);
        }
        mResultDialog.show();
    }

    private void startRotateAnimation() {
        if (mRotateAnimation == null) {
            mRotateAnimation = new RotateAnimation(0, 359, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            mRotateAnimation.setDuration(800);//跑一个周期所用时长
            mRotateAnimation.setRepeatCount(Animation.INFINITE);
            mRotateAnimation.setInterpolator(new LinearInterpolator());
        }
        if (!mRotateAnimation.hasStarted()) {
            iconRotate.startAnimation(mRotateAnimation);
        }
        tvUpgrading.setVisibility(View.VISIBLE);
    }

    private void stopRotateAnimation() {
        if (mRotateAnimation != null) {
            mRotateAnimation.cancel();
        }
        tvUpgrading.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_update:
//                tvProgress.setVisibility(View.VISIBLE);
//                progressBar.setVisibility(View.VISIBLE);
                btnUpdate.setVisibility(View.GONE);
                doUpdate();
                break;
        }
    }

//    private Runnable queryRunnable = new Runnable() {
//        @Override
//        public void run() {
//            doQuery();
//        }
//    };

//    private void doQuery(){
//        LLHttpManager.deviceUpgradeQuery(this, queryCode, new HttpCallback<HttpData<QueryCodeResultBean<FirmwareUpgradeBean, Object>>>(this) {
//            @Override
//            public void onStart(Call call) {
//            }
//
//            @Override
//            public void onSucceed(HttpData<QueryCodeResultBean<FirmwareUpgradeBean>> result) {
//                handleResult(result.getData());
//            }
//
//            @Override
//            public void onFail(Exception e) {
//                super.onFail(e);
//            }
//
//            @Override
//            public void onEnd(Call call) {
//            }
//        });
//    }

    private void doUpdate() {
        LLHttpManager.deviceUpgrade(this, upgradeType, serialNo, new HttpCallback<HttpData<QueryCodeResultBean<FirmwareUpgradeBean, Object>>>(this) {
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<FirmwareUpgradeBean, Object>> result) {
                startRotateAnimation();
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFirmwareUpdateEvent(FirmwareUpgradeInfoEvent event) {
        mFirmwareUpgradeInfoBean = event.mFirmwareUpgradeInfoBean;
//        mFirmwareUpgradeInfoBean.setUpgradeStateType(event.mFirmwareUpgradeBean.getStateType());
//        mFirmwareUpgradeInfoBean.setStep(event.mFirmwareUpgradeBean.getStep());
//        mFirmwareUpgradeInfoBean.setCurrentVersion(event.mFirmwareUpgradeBean.getCurrentVersion());
//        mFirmwareUpgradeInfoBean.setUpgradeVersion(event.mFirmwareUpgradeBean.getUpgradeVersion());
//        mFirmwareUpgradeInfoBean.setDescription(event.mFirmwareUpgradeBean.getDescription());
//        mFirmwareUpgradeInfoBean.setState(event.mFirmwareUpgradeBean.getState());
        updateView();
    }

    private void handleResult(QueryCodeResultBean<FirmwareUpgradeBean, Object> data) {
        queryCode = data.getQueryCode();
        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
        if (data != null) {
            switch (data.getQueryStateType()) {
                case 0:
                case 1:
//                    mHandler.postDelayed(queryRunnable, 1000);不需要轮询了，通过实时推送
                    break;
                case 2:
//                    showUpdateResultDialog(true);
                    break;
                case 3:
                case 4:
                case 5:
                    showUpdateResultDialog(false);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mHandler != null) {
//            mHandler.removeCallbacksAndMessages(null);
//        }
        EventBus.getDefault().unregister(this);
        stopRotateAnimation();
    }
}